package com.filldream.fastboot.common.util;

import cn.hutool.json.JSONUtil;
import com.filldream.fastboot.common.constant.FinalStr;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author RickSun
 * @Description 获取Request相关信息
 **/
public interface RequestContext {

    static final String UNKNOWN = "unknown";

    /**
     * @author RickSun
     * @Description 获取HttpServletRequest
     **/
     static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }

    /**
     * @author RickSun
     * @Description 获取指定请求头
     **/
     static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

    /**
     * @author RickSun
     * @Description 获取请求token
     **/
    static String getToken()  {
        String token = getHeader("token");
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        return token;
    }

    /**
     * @author RickSun
     * @Description 获取passtoken
     **/
    static String getPassToken()  {
        String passToken = getHeader(FinalStr.passToken);
        if(StringUtils.isEmpty(passToken)) {
            return null;
        }
        return passToken.toString();
    }

    /**
     * @author RickSun
     * @Description 获取Attribute
     **/
    static Object getAtt(String name) {
        return getRequest().getAttribute(name);
    }


    /**
     * @author RickSun
     * @Description 获取IP地址
     **/
    static String getIp() {
        return getRequest().getRemoteAddr();
    }


    /**
     * @author RickSun
     * @Description 获取浏览器类型
     * @date 2021/11/16 15:43
     * @return java.lang.String
     **/
    static String getBrowser() {
        UserAgent userAgent = UserAgent.parseUserAgentString(getRequest().getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        return browser.getName();
    }

    static String getUserAgentStr() {
        String header = getRequest().getHeader("User-Agent");
        return header;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    static String getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (StringUtils.isNotBlank(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return "";
        }
        return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList);
    }

    /**
     * @author RickSun
     * @Description 获取表单提交数据，一般用于GET
     * @date 2021/11/18 11:37
     * @return java.util.Map<java.lang.String,java.lang.String[]>
     **/
    static Map<String,String[]> getParameterMap(){
        return getRequest().getParameterMap();
    }

    /**
     * @author RickSun
     * @Description 获取表单提交数据，一般用于GET
     * @date 2021/11/18 11:39
     * @return java.lang.String
     **/
    static String getQueryString(){
        return getRequest().getQueryString();
    }


    /**
     * @author RickSun
     * @Description 获取IP
     * @date 2021/11/18 14:17
     * @return java.lang.String
     **/
    static String getIp2() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String comma = ",";
        String localhost = "127.0.0.1";
        if (ip.contains(comma)) {
            ip = ip.split(",")[0];
        }
        if (localhost.equals(ip)) {
            // 获取本机真正的ip地址
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException e) {
                System.out.println(e.getMessage());
            }
        }
        return ip;
    }

}
